
#include "main.h"

unsigned char ATD_Result = 0;


void AnalogInit( void )
{
	TRISA0 = 1;			  /* Set all analog pins as input */
	//TRISE0 = 1;

	ADCON1 = 0b00001110;	  /* b0-b3 -> AN0 - AN5 this inputs are analog; b4-b5 - references*/

	ADCON2 = 0b00010010;	  /* b0-b3 - divider(2 or 6 for 40MHz or more)  */
	                       /* b3-b5 - Tad = 4 */
 	                       /* b7 if set, then result is right justified */
   /* ADCON0 */
	ADCON0 = 1;				  /* Channel 0 + ATD module enable */
	
}

/* void ChSelect( byte ChNum ) */
/* { */
/* 	byte temp; */
/* 	temp = ADCON0; */
/* 	ChNum <<= 2; */
/* 	temp &= 0b11000011; */
/* 	temp |= ChNum; */
/* 	ADCON0 = temp; */
/* } */

void ATD( void )
{
	GODONE = 1;
	NOP();
	while(GODONE)
		continue;

	ATD_Result = ADRESH;
	
/* 	Result = (uint)ADRESH<<8; */
/* 	Result |= (uint)ADRESL; */
}

void Analog( void )
{
	unsigned int temp; 
	//ChSelect(0);
	ATD();
	
	/* Calculation Battery Capacity */
	temp = ATD_Result;
	if ( temp > 191 )
	{
		temp -= 191;					  /*  255 - 14V; 10.5V - 191;	*/
		temp *= 100;					  /* % */
		temp >>= 6;						  /*  */
	}
	else
		temp = 0;

	ATD_Result = temp;
}
 

/* Voltage of Battery (%) */
/* 	temp = ATD_Result; */
/* 	temp *= 100;					  /\* % *\/ */
/* 	temp >>= 8;						  /\*  *\/ */
/* 	ATD_Result = temp + 1; */
